package com.nageoffer.jobtrain.judge.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import com.nageoffer.jobtrain.common.web.exception.ClientException;
import com.nageoffer.jobtrain.judge.common.callback.DockerStartResultCallback;
import com.nageoffer.jobtrain.judge.common.callback.StatisticsCallback;
import com.nageoffer.jobtrain.judge.common.constant.SystemConstant;
import com.nageoffer.jobtrain.judge.common.constant.UserJudgeConstant;
import com.nageoffer.jobtrain.judge.common.enums.ExecuteJudeCodeEnums;
import com.nageoffer.jobtrain.judge.common.enums.UserPassOjQuestionEnums;
import com.nageoffer.jobtrain.judge.common.result.CompileResult;
import com.nageoffer.jobtrain.judge.common.result.SandBoxExecuteResult;
import com.nageoffer.jobtrain.judge.service.SandBoxService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 系统判题代码沙箱接口实现层
 * author：唐晨
 */
@Service
public class SandBoxServiceImpl implements SandBoxService {
    /**
     * docker主机地址
     */
    @Value("${sand-box.docker.host}")
    private String dockerHost;

    /**
     * 限制使用内存
     */
    @Value("${sand-box.limit.memory}")
    private Long memoryLimit;

    /**
     * 限制交互分区内存
     */
    @Value("${sand-box.limit.memory-swap}")
    private Long memorySwapLimit;

    /**
     * 限制CPU资源
     */
    @Value("${sand-box.limit.cpu}")
    private Long cpuLimit;

    /**
     * 限制运行时间
     */
    @Value("${sand-box.limit.time}")
    private Long timeLimit;

    /**
     * 操作docker客户端
     */
    private DockerClient dockerClient;

    /**
     * 容器ID
     */
    private String containerId;

    /**
     * 存放用户代码目录
     */
    private String userCodeDir;

    /**
     * 存放用户代码文件名
     */
    private String userCodeFileName;

    @Override
    public SandBoxExecuteResult executeJudeCode(String phoneNumber, String totalCode, List<String> inputList) {
        // 1、先创建代码存放本地目录
        createUserCodeFile(phoneNumber, totalCode);
        // 2、初始化docker容器配置，拉取镜像、创建容器等
        initDockerSanBox();
        // 3、进行代码的编译逻辑
        CompileResult compileResult = compileCodeByDocker();
        if (!compileResult.isCompiled()) {
            // 如果编译失败，直接删除容器信息以及代码文件信息
            deleteContainer();
            deleteUserCodeFile();
            return SandBoxExecuteResult.fail(ExecuteJudeCodeEnums.COMPILE_FAILED, compileResult.getErrorMessage());
        }
        // 4、此时编译逻辑正确，执行代码运行逻辑 -将数据库中预期输入测试用例，获取输出结果
        return executeJavaCodeByDocker(inputList);
    }

    private SandBoxExecuteResult executeJavaCodeByDocker(List<String> inputList) {
        List<String> outList = new ArrayList<>(); //记录输出结果
        long maxMemory = 0L;  //最大占用内存
        long maxUseTime = 0L; //最大运行时间
        //执行用户代码
        for (String inputArgs : inputList) {
            String cmdId = createExecCmd(UserJudgeConstant.DOCKER_JAVA_EXEC_CMD, inputArgs, containerId);
            //执行代码 - 代码运行时间监视器
            StopWatch stopWatch = new StopWatch();
            //执行情况监控
            StatsCmd statsCmd = dockerClient.statsCmd(containerId); //启动监控
            StatisticsCallback statisticsCallback = statsCmd.exec(new StatisticsCallback());
            stopWatch.start();
            DockerStartResultCallback resultCallback = new DockerStartResultCallback();
            try {
                dockerClient.execStartCmd(cmdId)
                        .exec(resultCallback)
                        .awaitCompletion(timeLimit, TimeUnit.SECONDS);  // 设置运行最长等待时间，如果超过了，代表可能是死循环问题
                if (UserPassOjQuestionEnums.FAILED.equals(resultCallback.getUserPassOjQuestionEnums())) {
                    //未通过所有用例返回结果
                    return SandBoxExecuteResult.fail(ExecuteJudeCodeEnums.NOT_ALL_PASSED);
                }
            } catch (Throwable ex) {
                throw new ClientException("代码运行时异常：" + ex);
            }
            stopWatch.stop();  //结束时间统计
            statsCmd.close();  //结束docker容器执行统计
            long userTime = stopWatch.getLastTaskTimeMillis(); //执行耗时
            maxUseTime = Math.max(userTime, maxUseTime);       //记录最大的执行用例耗时
            Long memory = statisticsCallback.getMaxMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, statisticsCallback.getMaxMemory()); //记录最大的执行用例占用内存
            }
            outList.add(resultCallback.getMessage().trim());   //记录正确的输出结果
        }
        deleteContainer();//删除容器
        deleteUserCodeFile(); //清理文件
        return getSanBoxResult(inputList, outList, maxMemory, maxUseTime); //封装结果
    }

    /**
     * 填充执行代码逻辑返回结果
     */
    private SandBoxExecuteResult getSanBoxResult(List<String> inputList, List<String> outList,
                                                 long maxMemory, long maxUseTime) {
        if (inputList.size() != outList.size()) {
            //输入用例数量 不等于 输出用例数量  属于执行异常
            return SandBoxExecuteResult.fail(ExecuteJudeCodeEnums.NOT_ALL_PASSED, outList, maxMemory, maxUseTime);
        }
        return SandBoxExecuteResult.success(ExecuteJudeCodeEnums.SUCCEED, outList, maxMemory, maxUseTime);
    }

    // 使用 docket中的 jdk进行对代码编译逻辑
    private CompileResult compileCodeByDocker() {
        String cmdId = createExecCmd(UserJudgeConstant.DOCKER_JAVAC_CMD, null, containerId);
        DockerStartResultCallback resultCallback = new DockerStartResultCallback();
        // 编译结果返回上层逻辑实体
        CompileResult compileResult = new CompileResult();
        try {
            dockerClient.execStartCmd(cmdId) // 执行编译命令
                    .exec(resultCallback) // 编译结果回调
                    .awaitCompletion();  // 阻塞等待编译结束
            if (UserPassOjQuestionEnums.FAILED.equals(resultCallback.getUserPassOjQuestionEnums())) {
                compileResult.setCompiled(false);
                compileResult.setErrorMessage(resultCallback.getErrorMessage());
            } else {
                compileResult.setCompiled(true);
            }
            return compileResult;
        } catch (Throwable ex) {
            //此处可以直接抛出 已做统一异常处理  也可再做定制化处理
            throw new ClientException("编译异常：" + ex);
        }
    }

    // 创建使用 docker 编译命令
    private String createExecCmd(String[] javaCmdArr, String inputArgs, String containerId) {
        if (!StrUtil.isEmpty(inputArgs)) {
            //当入参不为空时拼接入参 - 这里将输入参数进行分割，可参考牛客、LeetCode设计使用 ,分割
            String[] inputArray = inputArgs.split(",");
            javaCmdArr = ArrayUtil.append(UserJudgeConstant.DOCKER_JAVA_EXEC_CMD, inputArray);
        }
        // 此时输入参数为 null，代表只有编译指令
        ExecCreateCmdResponse cmdResponse = dockerClient.execCreateCmd(containerId)
                .withCmd(javaCmdArr)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .exec();
        return cmdResponse.getId();
    }

    // 初始化Docker容器配置
    private void initDockerSanBox() {
        DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(dockerHost)
                .build();
        dockerClient = DockerClientBuilder
                .getInstance(clientConfig)
                .withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
                .build();
        //拉取镜像
        pullJavaEnvImage();
        //创建容器  限制资源   控制权限
        HostConfig hostConfig = getHostConfig();
        CreateContainerCmd containerCmd = dockerClient
                .createContainerCmd(UserJudgeConstant.JAVA_ENV_IMAGE)
                .withName(UserJudgeConstant.JAVA_CONTAINER_NAME);
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        //记录容器id
        containerId = createContainerResponse.getId();
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();
    }

    //限制资源   控制权限 - 创建docker 限制配置
    private HostConfig getHostConfig() {
        HostConfig hostConfig = new HostConfig();
        //设置用户提交代码数据卷挂载目录，指定用户代码路径
        hostConfig.setBinds(new Bind(userCodeDir, new Volume(UserJudgeConstant.DOCKER_USER_CODE_DIR)));
        //限制docker容器使用资源
        hostConfig.withMemory(memoryLimit);
        hostConfig.withMemorySwap(memorySwapLimit);
        hostConfig.withCpuCount(cpuLimit);
        hostConfig.withNetworkMode("none");  //禁用网络
        hostConfig.withReadonlyRootfs(true); //禁止在root目录写文件
        return hostConfig;
    }

    //拉取java执行环境镜像 需要控制只拉取一次
    private void pullJavaEnvImage() {
        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        List<Image> imageList = listImagesCmd.exec();
        for (Image image : imageList) {
            String[] repoTags = image.getRepoTags();
            if (repoTags != null && repoTags.length > 0 && UserJudgeConstant.JAVA_ENV_IMAGE.equals(repoTags[0])) {
                return;
            }
        }
        // 否则从 hub拉取镜像
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(UserJudgeConstant.JAVA_ENV_IMAGE);
        try {
            pullImageCmd.exec(new PullImageResultCallback()).awaitCompletion();
        } catch (Throwable ex) {
            throw new ClientException("拉取镜像异常：" + ex);
        }
    }

    //创建并返回用户代码的文件
    private void createUserCodeFile(String phoneNumber, String userCode) {
        String examCodeDir = Paths.get("").toAbsolutePath().getParent().toString() + File.separator + UserJudgeConstant.EXAM_CODE_DIR;
        if (!FileUtil.exist(examCodeDir)) {
            FileUtil.mkdir(examCodeDir); //创建存放用户代码的目录
        }
        String time = LocalDateTimeUtil.format(LocalDateTime.now(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        //拼接用户代码文件格式
        userCodeDir = examCodeDir + File.separator + phoneNumber + SystemConstant.UNDERLINE_SEPARATOR + time;
        userCodeFileName = userCodeDir + File.separator + UserJudgeConstant.USER_CODE_JAVA_CLASS_NAME;
        FileUtil.writeString(userCode, userCodeFileName, SystemConstant.UTF8);
    }

    /**
     * 删除容器逻辑
     */
    private void deleteContainer() {
        //执行完成之后删除容器
        dockerClient.stopContainerCmd(containerId).exec();
        dockerClient.removeContainerCmd(containerId).exec();
        //断开和docker连接
        try {
            dockerClient.close();
        } catch (Throwable ex) {
            throw new ClientException("删除容器异常：" + ex);
        }
    }

    /**
     * 删除用户挂载卷代码
     */
    private void deleteUserCodeFile() {
        FileUtil.del(userCodeDir);
    }
}
